/**
 * 
 */
package edu.umd.clip.lm.tools;

import java.util.*;

import edu.berkeley.nlp.util.*;

import edu.umd.clip.lm.questions.Question;
import edu.umd.clip.lm.util.tree.*;
import edu.umd.clip.lm.model.*;

/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class CountQuestionsByOffset {
	public static class Options {
        @Option(name = "-tree", required = true, usage = "history tree XML file")
		public String tree;      
        @Option(name = "-word-only", required = false, usage = "count only word questions")
		public boolean wordOnly = false;      
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
        OptionParser optParser = new OptionParser(Options.class);
        Options opts = (Options) optParser.parse(args, true);
        
		BinaryTree<HistoryTreePayload> root = LanguageModel.loadXMLHistoryTree(opts.tree);

		final int MAX_OFFSET=5;
		ArrayList<int []> questionCountsByLevel = new ArrayList<int []>(100);
		ArrayList<BinaryTree<HistoryTreePayload>> currentNodes = new ArrayList<BinaryTree<HistoryTreePayload>>(1);
		currentNodes.add(root);
		
		int maxSeenOffset = 0;
		
		while(currentNodes.size() > 0) {
			ArrayList<BinaryTree<HistoryTreePayload>> nextNodes = new ArrayList<BinaryTree<HistoryTreePayload>>(currentNodes.size() * 2);
			int levelCounts[] = new int[MAX_OFFSET];
			
			for(BinaryTree<HistoryTreePayload> node : currentNodes) {
				if (node.isLeaf()) continue;
				nextNodes.add(node.getLeft());
				nextNodes.add(node.getRight());
				
				Question question = node.getPayload().question;
				if (opts.wordOnly && question.isAboutHidden()) continue;
				
				byte offset = question.getTimeOffset();
				offset = (byte) -(offset+1);
				levelCounts[offset] += 1;
				
				if (offset > maxSeenOffset) {
					maxSeenOffset = offset;
				}
			}
			
			questionCountsByLevel.add(levelCounts);
			currentNodes = nextNodes;
		}
		
		for(int i = 0; i<questionCountsByLevel.size(); ++i) {
			
			int totalCount = 0;
			int counts[] = questionCountsByLevel.get(i);
			for(int count : counts) {
				totalCount += count;
			}
			
			System.out.print(i);
			for(int j=0; j<=maxSeenOffset; ++j) {
				System.out.print(',');
				System.out.print(totalCount == 0 ? 0 : (float)counts[j]/totalCount);
			}
			System.out.println();
		}
	}

}
